package com.ces.knacky.controller.buynsell;

import java.io.IOException;
import java.io.InputStream;
import java.util.StringTokenizer;

import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.hibernate.classic.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ces.knacky.framework.controller.BaseController;

@Controller
public class PaymentController extends BaseController {

	// String totalAmount;

	/*
	 * public String getTotalAmount() { return totalAmount; }
	 */

	String selectedIdsTotal;

	public String getSelectedIdsTotal() {
		return selectedIdsTotal;
	}

	@ModelAttribute("netAmount")
	public void setSelectedIdsTotal(String selectedIdsTotal) {
		this.selectedIdsTotal = selectedIdsTotal;
		System.out.println(" selectedIdsTotal  ::::::::::::: "
				+ selectedIdsTotal);
	}

	/*
	 * @ModelAttribute("netAmount") public void setTotalAmount(String
	 * totalAmount) { this.totalAmount = totalAmount; }
	 */

	@RequestMapping("/makePayment.htm")
	public String makePayment(HttpSession session) {
		System.out.println("make Payment...selectedIdsTotal "
				+ selectedIdsTotal);
		session.setAttribute("grandAmount", selectedIdsTotal);
		return "makePayment";

	}

	@RequestMapping("/paymentDone.htm")
	public String paymentDone(HttpSession session) {
		String paymentResult = "failurePayment";
		System.out.println("inside paymentdone "+ session.getAttribute("grandAmount"));
		String amt = (String) session.getAttribute("grandAmount");		
		System.out.println("amt " + amt);
		
		String responseString = getResponse(amt);
		//Asumbtion that we get success
		responseString ="TIMESTAMP=2010%2d12%2d13T11%3a35%3a14Z&CORRELATIONID=12de653936541&ACK=Success&VERSION=56%2e0&BUILD=1620725&AMT=10%2e00&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M&TRANSACTIONID=59006615A5133915T";
		//session.setAttribute("responsefromserver", "responseString");
		if (responseString != null) {
			  
			String ackToken = getToken(responseString ,"ACK");
 			if (null != ackToken && ackToken.equalsIgnoreCase("Success")) {
				
				String transactionToken = getToken(responseString ,"TRANSACTIONID");
				if (null != transactionToken)
				{
					session.setAttribute("transactionId", transactionToken);					
				}
				
				String amtToken = getToken(responseString ,"AMT");
				if (null != amtToken)
				{
					session.setAttribute("netAmount", amtToken);					
				}
				
				paymentResult = "successPayment";
				return paymentResult;
				
			} else if (null != ackToken && ackToken.equalsIgnoreCase("Failure")) {
				String corelationToken = getToken(responseString ,"CORRELATIONID");
				session.setAttribute("corelationToken", corelationToken);
				paymentResult = "failurePayment";
				return paymentResult;
			}
		}
		return paymentResult;
	}
 
	public String getToken(String responseString, String token) {
		StringTokenizer stringTokenizer = new StringTokenizer(responseString,"&");
		String reqToken = null;
		String tokenValue[] = new String[2];
		while (stringTokenizer.hasMoreTokens()) {
			String tokenString = stringTokenizer.nextToken();
			// System.out.println("token  ::" + tokenString);
			if (tokenString.contains(token)) {
				reqToken = tokenString;
				break;
			}
		}		
		tokenValue = reqToken.split("=");
		if (tokenValue[1] != null)
			return (tokenValue[1].toString());
		return tokenValue[1].toString();
	}
	
	/*public String getAck(String responseString) {
		// String tempResponse =
		// "TIMESTAMP=2010%2d12%2d11T10%3a56%3a09Z&CORRELATIONID=176add2c601c&ACK=Success&VERSION=56%2e0&BUILD=1620725&AMT=1%2e10&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M&TRANSACTIONID=41L935833N4322426";
		StringTokenizer stringTokenizer = new StringTokenizer(responseString,"&");
		String ackToken = null;
		while (stringTokenizer.hasMoreTokens()) {
			String token = stringTokenizer.nextToken();
			System.out.println("token  ::" + token);
			if (token.contains("ACK")) {
				ackToken = token;
				break;
			}
		}
		System.out.println("Ack returned >>>>>>>>>>>>>> " + ackToken);
		if (ackToken.contains("Success")) {
			System.out.println("successfully payment done");
			return "success";
		} else if (ackToken.contains("Failure")) {
			System.out.println("failure in payment");
			return "failure";
		}
		return "success";
	}*/

	public String getResponse(String amt) {
		HttpClient client = new HttpClient();
		String responseString = null;
		String url = "https://api-3t.sandbox.paypal.com/nvp?USER=sarwaj_1291987585_biz_api1.persistent.co.in&METHOD=DoDirectPayment&PWD=1291987630&SIGNATURE=AZTCKJi-gX.Yl7j9EJSRSYJiS4RxAb4I5WDMqyA3fI6uIMjVZTB3.iwN&VERSION=56.0&PAYMENTACTION=Sale&IPADDRESS=10.77.25.42&ACCT=4530709717035148&CURRENCYCODE=USD&STREET=1+Main+St&STREET2=San+Jose&COUNTRYCODE=US&STARTDATE=112015&EXPDATE=122015&EMAIL=sarwaj_1291987585_biz%40persistent.co.in&CREDITCARDTYPE=VISA&firstName=testuser&lastName=testuser&CREDITCARDTYPE=Visa&creditCardNumber=4635985352027491&expdate_month=01&expdate_year=2012&CVV2=123&address1=1+Main+St&address2=&city=San+Jose&state=CA&zip=95131"
				+ "&AMT=" + amt;
		System.out.println("url send " + url);
		PostMethod post = new PostMethod(url);
		try {
			int statusCode = client.executeMethod(post);
			System.out.println("statusCode :: " + statusCode);
			InputStream in = post.getResponseBodyAsStream();
			responseString = post.getResponseBodyAsString();
			// System.out.println("InputStream :: " + in);
			System.out.println("response string :: " + responseString);
			
			return responseString;

		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return responseString;
	}

}
